package djboom.materials.display.page {
	import djboom.materials.Work;
	import djboom.materials.core.DataCore;
	import djboom.materials.display.elements.Instruction;
	import djboom.materials.display.elements.RoundedButton;
	import djboom.materials.display.elements.Window;
	import djboom.materials.display.test.Answer;
	import djboom.materials.display.test.Question;
	import djboom.materials.display.test.QuestionButton;
	import djboom.materials.events.PageEvent;
	import djboom.materials.events.WindowEvent;

	import org.casalib.display.CasaShape;
	import org.casalib.display.CasaSprite;
	import org.casalib.util.ArrayUtil;

	import flash.events.Event;
	import flash.events.MouseEvent;

	/**
	 * .
	 * <br>
	 * 
	 * @author DJ BooM 
	 * @since 08.04.2010
	 * 
	 */

	public class Test extends Page {

		// ----------------------------------------------------------------------------
		// Константы класса.
		// ----------------------------------------------------------------------------

		private static const INSTRUCTION_XML:XML = <instructions>
            <instruction>
                <text><![CDATA[Прежде, чем приступить к выполнению лабораторных работ, пройдите тестирование.]]></text>       
            </instruction>            
        </instructions>;

		// ----------------------------------------------------------------------------
		// Свойства класса.
		// ----------------------------------------------------------------------------

		private var _instruction:Instruction;

		private var _questionList:XMLList;
		private var _questionButtons:CasaSprite;
		private var _question:Question;
		private var _questionLineShape:CasaShape;
		private var _currentQuestionButton:QuestionButton;
		private var _currentQuestionID:int = 0;

		private var _answerCase:CasaSprite;
		private var _rightAnswerCounter:int = 0;
		private var _userAnswerArray:Array = new Array();		

		private var _window:Window;
		private var _simpleButton:RoundedButton;

		// ----------------------------------------------------------------------------
		// Конструктор.
		// ----------------------------------------------------------------------------

		public function Test() {
			super();
		}	 

		// ----------------------------------------------------------------------------
		// Методы класса.
		// ----------------------------------------------------------------------------

		private function createSingleTest():void {
			var questionXML:XML = _questionList[_currentQuestionID];
			
			var questionText:String = questionXML.child("text").toString();			var answersList:XMLList = questionXML.child("answers").child("answer");
			
			if (_question == null) {
				_question = new Question(questionText);
				_question.x = 38;
				_question.y = 220;
				addChild(_question);
			} else {
				_question.questionText = questionText;
			}
			
			createAnswers(answersList);
		}

		private function createAnswers(answersList:XMLList):void {
			if (_answerCase == null) {
				_answerCase = new CasaSprite();
				_answerCase.x = 60;				_answerCase.y = _question.y + _question.height + 20;
				addChild(_answerCase);
			}
			
			for each (var answerXML:XML in answersList) {
				var answerText:String = answerXML.child("text").toString();
				var answerCorrect:Boolean = answerXML.hasOwnProperty("istrue") ? true : false;
				
				var answer:Answer = new Answer(answerText, answerCorrect);
				answer.y = answerXML.childIndex() * 40;
				_answerCase.addChild(answer);
			}
		}

		private function clearAnswers():void {
			if (_answerCase != null) {
				while (_answerCase.numChildren) {
					var answer:Answer = _answerCase.getChildAt(0) as Answer;
                
					answer.destroy();
					answer = null;
				}
			}
		}

		private function nextQuestion(event:MouseEvent):void {
			checkAnswer();
			
			_rightAnswerCounter = 0;
			
			_currentQuestionButton.enabled = false;
			
			_currentQuestionID++;
			
			if (_currentQuestionID < _questionList.length()) {
				_currentQuestionButton = _questionButtons.getChildAt(_currentQuestionID) as QuestionButton;
				_currentQuestionButton.enabled = true;
			
				clearAnswers();
				createSingleTest();
			} else {
				_simpleButton.removeEventListener(MouseEvent.CLICK, nextQuestion);
				
				_simpleButton.destroy();
				_simpleButton = null;
				
				lockPage();
				
				var completeTest:uint = ArrayUtil.contains(_userAnswerArray, false);
				
				if (completeTest == 0) {
					Navigation.toggleEnabled(Page.WORK_1_PAGE_1, true);
					Navigation.toggleEnabled(Page.WORK_2_PAGE_1, true);
					Navigation.toggleEnabled(Page.TEST, false);
                    
					_window = new Window();
					_window.addEventListener(WindowEvent.CLOSE, showNavigationPage);
					_window.init("Поздравляем!", "Тестирование пройдено успешно. Вы допущены к выполнению лабораторных работ.");
				} else {
					_window = new Window();
					_window.addEventListener(WindowEvent.CLOSE, showConceptsPage);
					_window.init("Внимание!", "Тестирование показало, что вы не готовы к выполнению лабораторных работ. Изучите основные понятия еще раз.");
				}	

				addChild(_window);
			}
		}

		private function checkAnswer():void {
			for (var i:int = 0;i < _answerCase.numChildren;i++) {
				var answer:Answer = _answerCase.getChildAt(i) as Answer;
				
				
				if (answer.correct) {
					if (answer.clicked) {
						_rightAnswerCounter++;
					}
				} else {
					if (answer.clicked) {
						_rightAnswerCounter--;
					}
				}
			}
			
			var questionXML:XML = _questionList[_currentQuestionID];
			var totalAnswer:int = questionXML.descendants("istrue").length();
			
			if (_rightAnswerCounter == totalAnswer) {
				_userAnswerArray.push(true);
			} else {
				_userAnswerArray.push(false);
			}
		}

		private function showNavigationPage(event:WindowEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.NAVIGATION;
			dispatchEvent(pageEvent);
		}

		private function showConceptsPage(event:WindowEvent):void {
			var pageEvent:PageEvent = new PageEvent(PageEvent.CHANGE);
			pageEvent.pageName = Page.CONCEPTS;
			dispatchEvent(pageEvent);
		}

		// ----------------------------------------------------------------------------
		// Публичные методы.
		// ----------------------------------------------------------------------------

		override public function init():void {
			// Создаем заголовок страницы.
			createTitlePage("Допуск к работе");
			
			_instruction = new Instruction(INSTRUCTION_XML.child("instruction"));
			addChild(_instruction);
			
			/**
			 * Создаем цепочку с вопросами.
			 * 
			 */

			_questionList = DataCore.TEST_XML.child("question");
				 
			_questionLineShape = new CasaShape();
			_questionLineShape.graphics.lineStyle(2, 0x919191);
			_questionLineShape.graphics.moveTo(0, 0);
			_questionLineShape.graphics.lineTo(_questionList.length() * 90 - 25, 0);
			_questionLineShape.x = 20;			_questionLineShape.y = 169;
			addChild(_questionLineShape);

			_questionButtons = new CasaSprite();
			_questionButtons.x = 20;
			_questionButtons.y = 155;
			addChild(_questionButtons);
			
			for each (var questionXML:XML in _questionList) {
				var childIndex:int = questionXML.childIndex();
				
				var questionButton:QuestionButton = new QuestionButton(childIndex);
				questionButton.x = childIndex * 90;			
				_questionButtons.addChild(questionButton);
				
				if (childIndex == 0) {
					_currentQuestionButton = questionButton;
					_currentQuestionButton.enabled = true;
				}
			}
			
			createSingleTest();
			
			_simpleButton = new RoundedButton("Продолжить");
			_simpleButton.x = Work.WIDTH * 0.5 - _simpleButton.width * 0.5;
			_simpleButton.y = Work.HEIGHT - 118;
			_simpleButton.addEventListener(MouseEvent.CLICK, nextQuestion);
			addChild(_simpleButton);
		}

		
		override protected function clearPage(event:Event):void {
			super.clearPage(event);
			
			if (_window != null) {
				_window.destroy();
				_window = null;
			}
            
			_userAnswerArray = null;
            
			if (_simpleButton != null) {
				_simpleButton.destroy();
				_simpleButton = null;
			}

			_currentQuestionButton = null;
            
			clearAnswers();
            
			if (_answerCase != null) {
				_answerCase.destroy();
				_answerCase = null;
			}
            
			if (_question != null) {
				_question.destroy();
				_question = null;
			}
            
			if (_questionButtons != null) {
				while (_questionButtons.numChildren) {
					var questionButton:QuestionButton = _questionButtons.getChildAt(0) as QuestionButton;
                
					questionButton.destroy();
					questionButton = null;
				}
            
				_questionButtons.destroy();
				_questionButtons = null;
			}
            
			if (_questionLineShape != null) {
				_questionLineShape.destroy();
				_questionLineShape = null;
			}
            
			_questionList = null;
            
			_instruction.destroy();
			_instruction = null;
		}
        
		// ----------------------------------------------------------------------------
        // Публичные свойства.
        // ----------------------------------------------------------------------------
	}
}
